// index.js

const readline = require('readline');
const Calculator = require('./calculator');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const calculator = new Calculator();

const promptUser = () => {
    rl.question('请输入两个数字和运算符（如 1 + 2），输入 exit 退出: ', (input) => {
        if (input.trim().toLowerCase() === 'exit') {
            console.log('退出程序.');
            rl.close();
            return;
        }

        const parts = input.split(' ');

        if (parts.length !== 3) {
            console.log('无效输入，请输入格式为 "数字 运算符 数字"（如 1 + 2）.');
            promptUser();
            return;
        }

        const a = parseFloat(parts[0]);
        const operator = parts[1];
        const b = parseFloat(parts[2]);

        let result;

        try {
            switch (operator) {
                case '+':
                    result = calculator.add(a, b);
                    break;
                case '-':
                    result = calculator.subtract(a, b);
                    break;
                case '*':
                case 'x':
                    result = calculator.multiply(a, b);
                    break;
                case '/':
                    result = calculator.divide(a, b);
                    break;
                default:
                    console.log('无效运算符，请使用 +, -, *, /.');
                    promptUser();
                    return;
            }
            console.log(`结果: ${result}`);
        } catch (error) {
            console.log(error.message);
        }

        promptUser(); // 继续提示用户
    });
};

// 开始提示用户
promptUser();
